import axios from "axios";

// 全局配置
// axios.defaults.baseURL = 'http://localhost:3000';
// axios.defaults.timeout = 10000;

export function createAxios(options = {}) {
  return axios.create({ ...options });
}

// 实例级别
export const adminApi = createAxios({
  baseURL: "/api",
  timeout: 10000,
});

// 拦截器级
// 任何一个请求都包含 request 和 response
adminApi.interceptors.request.use(
  function (config) {
    // const {
    //   cats: { bigCats, smallCats ,accessToken},
    // } = useCatStore();
    if(localStorage.getItem("token")){
      config.headers.Authorization = localStorage.getItem("token");
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

adminApi.interceptors.response.use(
  function (response) {
    return response.data?.data || {}; // 提供默认值避免 undefined
  },
  async function (error) {
    // 全局错误处理
    const errorMessage = getErrorMessage(error);
    // ElMessage.error(errorMessage.message);
    // console.log("Error Data:", errorMessage);

    return Promise.reject(error);
  }
);

// 获取错误信息的辅助函数
function getErrorMessage(error) {
  let message = "未知错误";
  if (axios.isAxiosError(error)) {
    switch (error.response?.status) {
      case 400:
        message = "请求错误";
        break;
      case 401:
        message = "未授权，请登录";
        break;
      case 403:
        message = "拒绝访问";
        break;
      case 404:
        message = `请求地址出错: ${error.response.config.url}`;
        break;
      case 408:
        message = "请求超时";
        break;
      case 500:
        message = "服务器内部错误";
        break;
      case 501:
        message = "服务未实现";
        break;
      case 502:
        message = "网关错误";
        break;
      case 503:
        message = "服务不可用";
        break;
      case 504:
        message = "网关超时";
        break;
    }
  }
  return {
    code: error.response?.status,
    message: message,
  };
}

export default adminApi;